import json
from typing import Any, Dict, List
from datetime import datetime


def serialize_card(card) -> Dict[str, str]:
    """序列化牌对象为字典"""
    return {"rank": card.rank.symbol, "suit": card.suit.value}


def serialize_player(player) -> Dict[str, Any]:
    """序列化玩家对象为字典"""
    return {
        "name": player.name,
        "chips": player.chips,
        "current_bet": player.current_bet,
        "folded": player.folded,
        "all_in": player.all_in,
        "is_ai": player.is_ai
    }


def validate_bet_amount(amount: int, player_chips: int, current_bet: int, min_bet: int) -> tuple[bool, str]:
    """验证下注金额是否合法"""
    if amount < 0:
        return False, "下注金额不能为负数"

    if amount > player_chips:
        return False, "下注金额超过玩家筹码"

    if amount < min_bet and amount != player_chips:  # 除非全押
        return False, f"下注金额不能少于最小下注额 {min_bet}"

    return True, "下注金额合法"


def validate_player_action(action: str, valid_actions: List[str]) -> tuple[bool, str]:
    """验证玩家行动是否合法"""
    if action not in valid_actions:
        return False, f"无效行动 {action}，有效行动: {valid_actions}"

    return True, "行动合法"


def get_timestamp() -> str:
    """获取当前时间戳字符串"""
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


def log_game_event(event_type: str, data: Dict[str, Any]):
    """记录游戏事件日志"""
    log_entry = {
        "timestamp": get_timestamp(),
        "event_type": event_type,
        "data": data
    }
    print(f"[GAME LOG] {json.dumps(log_entry, ensure_ascii=False)}")


def calculate_pot_odds(pot_size: int, bet_to_call: int) -> float:
    """计算底池赔率"""
    if bet_to_call <= 0:
        return 0.0

    return pot_size / (pot_size + bet_to_call)


def format_chips(amount: int) -> str:
    """格式化筹码显示"""
    if amount >= 1000000:
        return f"{amount / 1000000:.1f}M"
    elif amount >= 1000:
        return f"{amount / 1000:.1f}K"
    else:
        return str(amount)


class GameError(Exception):
    """游戏相关错误"""

    def __init__(self, message: str, code: str = None):
        self.message = message
        self.code = code
        super().__init__(self.message)


class ValidationError(GameError):
    """验证错误"""
    pass


class GameStateError(GameError):
    """游戏状态错误"""
    pass